package com.concurrent.test1;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: zhouyang
 * @descrpition: 两个线程交替打印奇偶
 * @time: 2019-05-09 20:36
 */
@Slf4j
public class IntegrationPrint {
    private static int count = 0;

    private static ReentrantLock reentrantLock = new ReentrantLock();

    private static Condition condition = reentrantLock.newCondition();

    public static void main(String[] args) {
        Thread thread1 = new Thread(()->{

            while(count < 100){
                reentrantLock.lock();
                if(count % 2 == 0){
                    log.info("thread 1 :{}",count);
                    count++;
                    condition.signal();//唤醒
                }else{
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                reentrantLock.unlock();
            }

        });
        Thread thread2 = new Thread(()->{

            while(count < 100){
                reentrantLock.lock();
                if( count % 2 == 1){
                    log.info("thread 2 :{}",count);
                    count++;
                    condition.signal();//唤醒
                }else{
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                reentrantLock.unlock();
            }

        });

        thread1.start();
        thread2.start();
    }


}
